﻿using iWareModels;
using XiangziProjectTemplete.Core.Api.Common;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// Agv任务控制器 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Les_AgvTaskController : ControllerBase
    {
        private readonly IUserRoleServices _userRoleServices;
        private readonly ILes_AgvTaskServices _Les_AgvTaskServices;
        private readonly IUser _user;
        private readonly ILes_ProcedureRoleServices _les_ProcedureRoleServices;
        public Les_AgvTaskController(IUserRoleServices userRoleServices, ILes_ProcedureRoleServices les_ProcedureRoleServices, ILes_AgvTaskServices Les_AgvTaskServices, IUser user)
        {
            this._userRoleServices = userRoleServices;
            this._les_ProcedureRoleServices = les_ProcedureRoleServices;
            _Les_AgvTaskServices = Les_AgvTaskServices;
            _user = user;
        }

        /// <summary> 
        /// 分页获取Agv任务列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<AgvTaskViewModel>>> Get([FromBody] Les_AgvTaskParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<Les_AgvTask, Les_AgvTaskParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<AgvTaskViewModel>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }

            #region 根据工序权限进行过滤
            /*
            var proListByUserResult = await _les_ProcedureRoleServices.GetProcedureListByUser(_user);
            if (proListByUserResult.success == false)
            {
                return MessageModel<PageModel<AgvTaskViewModel>>.Fail(proListByUserResult.msg);
            }
            SeeProcedureRoleViewModel seeProcedureRoleViewModel = proListByUserResult.response;
            List<int> proList = new List<int>();
            if (seeProcedureRoleViewModel.IsHasAllProcedure)
            {//全部权限

            }
            else
            {
                proList = seeProcedureRoleViewModel.ProcedureList;
                Expression<Func<AgvTaskViewModel, bool>> whereExpression2 = a => a. != null && proList.Contains(Convert.ToInt32(a.AllowProcedure));
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }
            //*/
            #endregion

            #region 根据是否管理员进行过滤

            bool isManagerRole = await LesApiCommon.IsManagerRole(_userRoleServices, _user);
            if (isManagerRole == false)
            {
                Expression<Func<Les_AgvTask, bool>> whereExpression2 = a => a.CreateId == _user.ID;
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }

            #endregion


            var data = await _Les_AgvTaskServices.QueryPage(whereConditions.data, param.page, param.pageSize, " CreateTime desc ");
            //转换
            var newQueryData = ListHelper.T1ToT2<PageModel<Les_AgvTask>, PageModel<AgvTaskViewModel>>(data);
            foreach (var item in newQueryData.data)
            {
                //item.TaskStatusName = EnumberHelper.GetEnumDescription((TaskStatusEnum)Enum.Parse(typeof(TaskStatusEnum), item.TaskStatus.ToString()));
                //item.TaskTypeName = EnumberHelper.GetEnumDescription((AGVTaskType)Enum.Parse(typeof(AGVTaskType), item.TaskType.ToString()));
            }
            return new MessageModel<PageModel<AgvTaskViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = newQueryData
            };

        }


        /// <summary> 
        /// 分页获取Agv任务列表,增加 未完成的 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<PageModel<AgvTaskViewModel>>> GetForNoFinished([FromBody] Les_AgvTaskParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<Les_AgvTask, Les_AgvTaskParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<AgvTaskViewModel>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }

            #region 根据工序权限进行过滤
            /*
            var proListByUserResult = await _les_ProcedureRoleServices.GetProcedureListByUser(_user);
            if (proListByUserResult.success == false)
            {
                return MessageModel<PageModel<AgvTaskViewModel>>.Fail(proListByUserResult.msg);
            }
            SeeProcedureRoleViewModel seeProcedureRoleViewModel = proListByUserResult.response;
            List<int> proList = new List<int>();
            if (seeProcedureRoleViewModel.IsHasAllProcedure)
            {//全部权限

            }
            else
            {
                proList = seeProcedureRoleViewModel.ProcedureList;
                Expression<Func<AgvTaskViewModel, bool>> whereExpression2 = a => a. != null && proList.Contains(Convert.ToInt32(a.AllowProcedure));
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }
            //*/
            #endregion

            #region 根据是否管理员进行过滤

            bool isManagerRole = await LesApiCommon.IsManagerRole(_userRoleServices, _user);
            if (isManagerRole == false)
            {
                Expression<Func<Les_AgvTask, bool>> whereExpression2 = a => a.CreateId == _user.ID;
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }

            #endregion

            #region 增加未完成状态筛选

            Expression<Func<Les_AgvTask, bool>> whereExpression3 = a => (a.TaskStatus == Convert.ToInt32(TaskStatusEnum.已下发) || a.TaskStatus == Convert.ToInt32(TaskStatusEnum.未开始));
            whereConditions.data = whereConditions.data.And(whereExpression3);

            #endregion


            var data = await _Les_AgvTaskServices.QueryPage(whereConditions.data, param.page, param.pageSize, " CreateTime desc ");
            //转换
            var newQueryData = ListHelper.T1ToT2<PageModel<Les_AgvTask>, PageModel<AgvTaskViewModel>>(data);
            foreach (var item in newQueryData.data)
            {
                //item.TaskStatusName = EnumberHelper.GetEnumDescription((TaskStatusEnum)Enum.Parse(typeof(TaskStatusEnum), item.TaskStatus.ToString()));
                //item.TaskTypeName = EnumberHelper.GetEnumDescription((AGVTaskType)Enum.Parse(typeof(AGVTaskType), item.TaskType.ToString()));
            }
            return new MessageModel<PageModel<AgvTaskViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = newQueryData
            };

        }

        /// <summary> 
        /// 获取单个Agv任务 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Les_AgvTask>> Get(int id = 0)
        {
            return new MessageModel<Les_AgvTask>()
            {
                msg = "获取成功",
                success = true,
                response = await _Les_AgvTaskServices.QueryById(id)
            };
        }

        /// <summary> 
        /// 根据 AGV任务表的ID或者任务号 查找 该任务的详细阶段列表 
        /// </summary> 
        /// <param name="agvTaskId">AGV任务表的ID或者是任务号</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<List<Les_AgvTaskPhase>>> GetAgvTaskPhaseList(string agvTaskId)
        {
            List<Les_AgvTaskPhase> list = await _Les_AgvTaskServices.GetAgvTaskPhaseList(agvTaskId);
            if (list == null || list.Count == 0)
            {
                list = await _Les_AgvTaskServices.GetAgvTaskPhaseListByTaskNo(agvTaskId);
            }
            return new MessageModel<List<Les_AgvTaskPhase>>()
            {
                msg = "获取成功",
                success = true,
                response = list
            };
        }

        /// <summary> 
        /// 新增Agv任务 
        /// </summary> 
        /// <param name="request">要新增的Agv任务对象</param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] Les_AgvTask request)
        {
            var data = new MessageModel<string>();

            request.CreateTime = request.ModifyTime = DateTime.Now;
            request.CreateBy = request.ModifyBy = _user.Name;
            request.CreateId = request.ModifyId = _user.ID;
            request.OperationRemark = "添加";
            var id = await _Les_AgvTaskServices.Add(request);
            data.success = id > 0;

            if (data.success)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }

            return data;
        }

        /// <summary> 
        /// 更新Agv任务 
        /// </summary> 
        /// <param name="request">要更新的Agv任务对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] Les_AgvTask request)
        {
            var data = new MessageModel<string>();
            if (request.Id != string.Empty)
            {
                request.ModifyTime = DateTime.Now;
                request.ModifyBy = _user.Name;
                request.ModifyId = _user.ID;
                request.OperationRemark = "更新";
                data.success = await _Les_AgvTaskServices.Update(request);
                if (data.success)
                {
                    data.msg = "更新成功";
                    data.response = request?.Id.ObjToString();
                }
            }

            return data;
        }

        /// <summary> 
        /// 删除Agv任务 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var detail = await _Les_AgvTaskServices.QueryById(id);
                if (detail != null)
                {
                    data.success = await _Les_AgvTaskServices.DeleteById(detail.Id);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }

            return data;
        }
    }
}
